﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using SPWeiBo.Repositories;
using Microsoft.SharePoint;
using System.Web.Script.Serialization;

namespace SPWeiBo.Layouts.SPWeiBo
{
    public class Services : IHttpHandler
    {
        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            var action = context.Request.Params["action"];

            if (action == "get")
            {
                DateTime after;
                if (!DateTime.TryParse(context.Request.Params["after"], out after))
                {
                    after = new DateTime(1979, 1, 1);
                }
                var json = ReturnWeiBoItems(after);

                context.Response.Clear();            
                context.Response.ContentType = "application/json";
                context.Response.Write(json);
            }
            else if (action == "post")
            {
                var content = context.Request.Params["content"];
                if (!String.IsNullOrEmpty(content))
                {
                    new WeiBoRepository(SPContext.Current.Web).CreateWeiBoItem(content, SPContext.Current.Web.CurrentUser);
                }
            }
            else if (action == "follow")
            {
                var follow = context.Request.Params["follow"];
                if (!String.IsNullOrEmpty(follow))
                {
                    new WeiBoRepository(SPContext.Current.Web).CreateFollowingRelation(SPContext.Current.Web.CurrentUser, follow);
                }
            }
        }

        private String ReturnWeiBoItems(DateTime after)
        {
            //var weiBoItems = new WeiBoRepository(SPContext.Current.Web)
            //    .ReadLatestWeiBoItems(SPContext.Current.Web.CurrentUser.LoginName, after, 20)
            //    .Select(i => new
            //    {
            //        content = i.Content,
            //        author = i.Author.Name,
            //        timeCreated = i.TimeCreated
            //    });
            //var weiBoItemsJson = new JavaScriptSerializer().Serialize(weiBoItems);
            //return weiBoItemsJson;
            return null;
        }
    }
}
